package com.cwits.wifi.ui.dialog;

import android.app.DialogFragment;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseDialogFragment;
import com.cwits.wifi.data.beans.DeviceIPInfo;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.IConstant;

import java.util.ArrayList;

/**
 * Created by ZhangHua on 16-03-01.
 */
public class DeviceIPListDialog extends BaseDialogFragment implements IConstant, IAction {
    private final String tag = getClass().getSimpleName();
    private ListView mListView;
    private DeviceAdapter mAdapter;
    private NotifyDialog mRefreshDialog;
    private ArrayList<DeviceIPInfo> iplist = new ArrayList<>();
    private final Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
        setCancelable(false);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Dbug.d(tag, "------onCreateView--------:");
        View view = inflater.inflate(R.layout.device_list_dialog, container, false);
        TextView dialog_title = (TextView) view.findViewById(R.id.dialog_title);
        dialog_title.setText(getString(R.string.select_ip));
        mListView = (ListView) view.findViewById(android.R.id.list);
        TextView exitText = (TextView) view.findViewById(R.id.exit_action);
        exitText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //getActivity().sendBroadcast(new Intent(ACTION_QUIT_APP));
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onCancle();
                }
                dismiss();

            }
        });

        TextView refresh = (TextView) view.findViewById(R.id.refresh_button);
        refresh.setVisibility(View.GONE);
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshDialog = new NotifyDialog(true, R.string.please_wait);
                mRefreshDialog.show(getFragmentManager(), "mRefreshDialog");
                mHandler.post(scanWifiTask);
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String selectedSSID = mList.get(position).get(TEXT).toString();
                DeviceIPInfo scanResult = mAdapter.getItem(position);
                String selectedSSID = scanResult.IP;
                dismiss();
                Dbug.d(tag, "Wi-Fi is already connected:" + selectedSSID);
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(true, selectedSSID);
                }
            }
        });
        return view;
    }

    private OnItemClickListener mOnItemClickListener;
    public void setOnItemClickListener(OnItemClickListener listener){
        mOnItemClickListener = listener;
    }
    public interface OnItemClickListener{
        void onItemClick(boolean isConnected, String ip);
        void onCancle();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        final WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();

        params.width = 100;
        params.height = 150;
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
            params.width = displayMetrics.heightPixels * 4 / 5;
            params.height = displayMetrics.heightPixels * 3 / 4;
        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
            params.width = displayMetrics.widthPixels * 4 / 5;
            params.height = displayMetrics.widthPixels * 3 / 4;
        }
        params.gravity = Gravity.CENTER;
        getDialog().getWindow().setAttributes(params);

        mAdapter = new DeviceAdapter(getActivity());
        mListView.setAdapter(mAdapter);
        //mHandler.post(updateWifiTask);
    }

    private final int SCAN_TIME = 5;
    private int mTime = 0;
    private final int UPDATE_SCAN_TIME = 15;
    private int UPDATE_Time = 0;

    private Runnable scanWifiTask = new Runnable() {
        @Override
        public void run() {
            if (mTime >= SCAN_TIME){
                mTime = 0;
                Dbug.i(tag,"--------------updateWifiTask-time:" + mTime);
                mHandler.removeCallbacks(scanWifiTask);
                if (mRefreshDialog != null && mRefreshDialog.isShowing()) {
                    mRefreshDialog.dismiss();
                }
                if(UPDATE_Time < UPDATE_SCAN_TIME)
                    mHandler.postDelayed(updateWifiTask, 300);
                refreshList();
            } else {
                mTime ++;
                mHandler.removeCallbacks(updateWifiTask);
                mHandler.postDelayed(scanWifiTask, 500);
            }
        }
    };
    public void setDeviceIPs(ArrayList<DeviceIPInfo> list){
        iplist.clear();
        for (int i = 0;i < list.size();i++){
            iplist.add(list.get(i));
        }
        mHandler.post(updateWifiTask);
    }

    private Runnable updateWifiTask = new Runnable() {
        @Override
        public void run() {
            refreshList();
        }
    };

    private void refreshList(){
        mAdapter.clear();
        mAdapter.addAll(iplist);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        mHandler.removeCallbacks(updateWifiTask);
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    private class DeviceAdapter extends ArrayAdapter<DeviceIPInfo>{
        private final LayoutInflater mLayoutInflater;
        private ViewHolder mViewHolder;

        public DeviceAdapter(Context context) {
            super(context, 0);
            mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null){
                convertView = mLayoutInflater.inflate(R.layout.device_list_item, parent, false);
                mViewHolder = new ViewHolder();
                mViewHolder.textView = (TextView) convertView.findViewById(R.id.text);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            final DeviceIPInfo systemInfo = getItem(position);
            mViewHolder.textView.setText(systemInfo.IP);
            return convertView;
        }

        private class ViewHolder {
            private TextView textView;
        }
    }
}
